// 登录逻辑
document.getElementById('loginForm')?.addEventListener('submit', async (e) => {
    e.preventDefault();

    const response = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            card_id: document.getElementById('card_id').value,
            password: document.getElementById('password').value
        })
    });

    const data = await response.json();
    const messageEl = document.getElementById('message');

    if (data.success) {
        window.location.href = '/dashboard';
    } else {
        messageEl.textContent = data.message;
        messageEl.style.display = 'block';
    }
});

// 仪表盘逻辑
if (window.location.pathname === '/dashboard') {
    loadAccountInfo();

    // 存款操作
    document.getElementById('depositBtn').addEventListener('click', async () => {
        const amount = parseFloat(document.getElementById('amount').value);

        if (isNaN(amount) || amount <= 0) {
            alert('请输入有效金额');
            return;
        }

        const response = await fetch('/api/deposit', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ amount: amount })
        });

        const result = await response.json();
        alert(result.message);
        if (result.success) {
            document.getElementById('balance').textContent = result.balance.toFixed(2);
            document.getElementById('amount').value = '';
        }
    });

    // 退出登录
    document.getElementById('logoutBtn').addEventListener('click', async () => {
        await fetch('/api/logout', { method: 'POST' });
        window.location.href = '/';
    });

    // 刷新余额
    document.getElementById('refreshBtn').addEventListener('click', loadAccountInfo);
}

// 加载账户信息
async function loadAccountInfo() {
    const response = await fetch('/api/account');
    const data = await response.json();

    if (data.success) {
        document.getElementById('customerName').textContent = data.data.customer_name;
        document.getElementById('cardId').textContent = data.data.card_id;
        document.getElementById('balance').textContent = data.data.balance.toFixed(2);
    } else {
        alert(data.message);
        window.location.href = '/';
    }
}

